package cn.xiaohuodui.util;

import cn.xiaohuodui.exceptions.BussException;
import cn.xiaohuodui.res.JsonRes;
import groovy.util.logging.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by TR on 2018/3/30.
 */
@ControllerAdvice
@lombok.extern.slf4j.Slf4j
public class BussExceptionHandler {

    public static final String ERROR_VIEW="error";

    public static boolean  isAjax(HttpServletRequest req){
        return (req.getHeader("X-Requested-With")!=null&&"XMLHttpRequest".equals(req.getHeader("X-Requested-With").toString()));
    }


    @ExceptionHandler(value = BussException.class)
    public Object errorHandler(HttpServletRequest req, HttpServletResponse res, BussException e){

        e.printStackTrace();

        if(isAjax(req)){
            return JsonRes.createByErrorCodeMessage(e.getCode(),e.getMessage());
        }else{
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("exception",e);
            modelAndView.addObject("errorUrl",req.getRequestURL());
            modelAndView.setViewName(ERROR_VIEW);
            return modelAndView;
        }
    }
}
